package cn.tannn.captcha.api.impl;

import cn.tannn.captcha.api.CaptchaCacheService;
import cn.tannn.captcha.api.GuavaCache;
import cn.tannn.captcha.sdk.config.CaptchaSetting;
import cn.tannn.captcha.sdk.module.CaptchaVO;
import cn.tannn.captcha.sdk.util.IpUtil;
import cn.tannn.captcha.sdk.util.StorageUtil;
import com.google.common.cache.Cache;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
 * 验证码缓存服务
 *
 * @author tnnn
 * @version V1.0
 * @date 2022-11-21 13:25
 */
public class CaptchaCacheLocalServiceImpl implements CaptchaCacheService {

    private static final Logger LOG = LoggerFactory.getLogger(CaptchaCacheLocalServiceImpl.class);

    private final CaptchaSetting captchaSetting;

    public CaptchaCacheLocalServiceImpl(CaptchaSetting captchaSetting) {
        this.captchaSetting = captchaSetting;
    }

    @Override
    public CaptchaSetting captchaSetting() {
        return captchaSetting;
    }


    @Override
    public void storageImageCaptcha(CaptchaVO captcha, HttpServletRequest request) {
        String key = IpUtil.getPoxyIpEnhance(request);
        // local兜底
        Cache<String, CaptchaVO> cache = GuavaCache.imageCaptchaCache(captcha.getOvertime());
        cache.put(key, captcha);
    }

    @Override
    public Optional<CaptchaVO> loadImageCaptcha(HttpServletRequest request) {
        String key = IpUtil.getPoxyIpEnhance(request);
        return loadImageCaptcha(key);
    }

    @Override
    public Optional<CaptchaVO> loadImageCaptcha(String ip) {
        String redisFolderKey = StorageUtil.storageCaptchaRedisFolder(captchaSetting.getPrefix(), ip);
        // local兜底
        Cache<String, CaptchaVO> cache = GuavaCache.imageCaptchaCache(captchaSetting.getExpireTime());
        CaptchaVO captchaVO = cache.getIfPresent(ip);
        cache.invalidate(ip);
        return Optional.ofNullable(captchaVO);
    }

    @Override
    public void deleteImageCaptcha(HttpServletRequest request) {
        String key = IpUtil.getPoxyIpEnhance(request);
        deleteImageCaptcha(key);
    }

    @Override
    public void deleteImageCaptcha(String ip) {
        try {
            Cache<String, CaptchaVO> cache = GuavaCache.imageCaptchaCache(captchaSetting.getExpireTime());
            cache.invalidate(ip);
        } catch (Exception e) {
            LOG.error("删除过期验证码失败", e);
        }
    }
}
